package com.jsmtr.rms.controller;

import java.util.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jsmtr.rms.entity.*;
import com.jsmtr.rms.service.*;
import com.jsmtr.rms.utils.DateTools;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.jsmtr.rms.entity.vo.NZUserForm;
import com.jsmtr.rms.utils.EnumTools;
import org.springframework.web.bind.annotation.ResponseBody;


@Controller
@RequestMapping("/Do/NZResume")
public class DoNZResumeController {

    @Resource
    private IUtilService utilService;

    @Resource
    private IDoSZService szService;

    @Resource
    private INZService nzService;

    @Resource
    private IDoResumeService doResumeService;

    @Resource
    private IProjectService projectService;

    //[start] 查询应聘者信息

    //首页
    @RequestMapping("/")
    public String Index(HttpServletRequest request, Model model) {
        try {
            model.addAttribute("path", request.getContextPath());
            String pid = request.getParameter("pid").trim();
            String fid = request.getParameter("fid").trim();
            String deptcode = request.getParameter("deptcode").trim();

            model.addAttribute("pid", pid);
            model.addAttribute("fid", fid);
            model.addAttribute("deptcode", deptcode);

            ProjectInfoFlow projectInfoFlow= projectService.getFolwById(fid);
            if(projectInfoFlow!=null){
                model.addAttribute("nowflow",projectInfoFlow.getNickname());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "Do/Internal/Resume/index";
    }
/*
    @SuppressWarnings("unchecked")
    @RequestMapping("/getusers")
    public void getusers(HttpServletRequest request, HttpServletResponse response, DNZResume user) {
        try {
            int perpage = Integer.parseInt(request.getParameter("perpage"));
            int page = Integer.parseInt(request.getParameter("page"));
            String flowid = request.getParameter("flowid").trim();
            user.setPath("/" + flowid + "/");

            Map<String, Object> map = nzService.getUsers(page, perpage, user);
            StringBuilder result = new StringBuilder();
            double pageCount = (Double) map.get("pageCount");
            double allcount = (Double) map.get("count");

            if (pageCount != 0) {
                Object object = map.get("list");
                int num = 0;
                for (DNZResume _user : (List<DNZResume>) object) {
                    result.append("<tr><td><input type='checkbox' id='cb_" + _user.getId() + "'></td>");
                    result.append("<td>" + (perpage * (page - 1) + num + 1) + "</td>");
                    result.append("<td>" + _user.getCode() + "</td>");
                    result.append("<td class='link'><a target='_blank' href='"
                            + request.getContextPath() + "/Do/NZApply/View?id="
                            + _user.getId() + "'>" + _user.getName()
                            + "</a></td>");
                    result.append("<td>" + _user.getSex() + "</td>");
                    result.append("<td>" + _user.getAge() + "</td>");
                    result.append("<td>" + _user.getZzmm() + "</td>");
                    result.append("<td>" + _user.getBirthday() + "</td>");
                    result.append("<td>" + _user.getGroupdate() + "</td>");
                    result.append("<td>" + _user.getEducation() + "</td>");
                    result.append("<td>" + _user.getTel() + "<input type='hidden' name='resume[" + num + "].id' value='" + _user.getId() + "' /></td>");
                    result.append("<td class='sxbzbtn' id='" + _user.getId() + "'>" + (_user.getSxbz() == null ? "" : _user.getSxbz()) + "</td>");
                    result.append("<td><div><select name='resume[" + num + "].state'>");
                    result.append("<option value='未处理'>未处理</option><option value='通过'>通过</option><option value='未通过'>未通过</option>");
                    result.append("</select><input type='hidden' value='" + _user.getState() + "' /></div></td>");

                    if (_user.getState().equals("未处理")) {
                        result.append("<td class='true'><span>未完成</td></tr>");
                    } else if (_user.getState().equals("未通过")) {
                        result.append("<td class='false'><span>已完成</td></tr>");
                    } else {
                        if (_user.getFid().equals(flowid)) {
                            result.append("<td class='true'><span>未完成</td></tr>");
                        } else {
                            result.append("<td class='false'><span>已完成</td></tr>");
                        }
                    }

                    num++;
                }
            } else {
                result.append("<tr style='display:none'><td></td></tr>");
            }
            result.append("<input type='hidden' id='pageCount' value='" + pageCount + "' />");
            result.append("<input type='hidden' id='allCount' value='" + allcount + "' />");
            utilService.printTextResult(result.toString(), response);
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printTextResult("<tr><td colspan='11'>读取数据失败</td></tr><input type='hidden' id='pageCount' value='0' /><input type='hidden' id='allCount' value='0' />", response);
        }

    }*/

    //获取人员列表
    @ResponseBody
    @RequestMapping(value = "/getNzResumeListLayuiJson", method = RequestMethod.GET)
    public LayuiDataTableResultBean getNzResumeListLayuiJson(HttpServletRequest request, DUserResume user) {
        try {
            int page = Integer.parseInt(request.getParameter("page"));
            int limit = Integer.parseInt(request.getParameter("limit"));
            String flowid = request.getParameter("flowid").trim();

           /* user.setPath("/" + flowid + "/");
            Map<String, Object> _map = new HashMap<String, Object>();
            Map<String, Object> map = nzService.getUsers(page, limit, user);*/
            Map<String, Object> _map = new HashMap<String, Object>();
            _map.put("agefrom", request.getParameter("agefrom").trim());
            _map.put("ageto", request.getParameter("ageto").trim());
            _map.put("workyearfrom", request.getParameter("workyearfrom").trim());
            _map.put("workyearto", request.getParameter("workyearto").trim());
            _map.put("heightfrom", request.getParameter("heightfrom").trim());
            _map.put("heightto", request.getParameter("heightto").trim());
            _map.put("rcount",request.getParameter("rcount").trim());
            _map.put("mcontent",request.getParameter("mcontent"));

            Map<String, Object> map = szService.getResumesMap(page, limit, user, _map);


            double pageCount = (Double) map.get("pageCount");
            double allcount = (Double) map.get("count");

            JSONArray jsonArray = new JSONArray();
            int num = 1;
            if (pageCount != 0) {
                List<HashMap> object = (List<HashMap>)map.get("list");
                for (HashMap<String,Object> _user :  object) {
                    JSONObject jsonObject = new JSONObject();
                    NZResume nzResume = nzService.getResumeByCardno(_user.get("CARDNO").toString());
                    if(nzResume != null){
                        jsonObject.put("JOBNUMBER", (nzResume.getCode()==null?"":nzResume.getCode()));
                        jsonObject.put("GROUPDATE", (nzResume.getGroupdate()==null?"":nzResume.getGroupdate()));
                    }else {
                        jsonObject.put("JOBNUMBER", "");
                        jsonObject.put("GROUPDATE", "");
                    }

                    jsonObject.put("id_cb","cb_" + _user.get("ID"));
                    jsonObject.put("id",limit * (page - 1) + num);
                    jsonObject.put("cardcount", Integer.parseInt(_user.get("CARDCOUNT").toString()));
                    jsonObject.put("ContextPath",request.getContextPath()+"/Do/NZApply/View?id=" + _user.get("ID"));
                    jsonObject.put("NAME", _user.get("NAME"));
                    jsonObject.put("SEXNAME", _user.get("SEXNAME"));
                    jsonObject.put("BIRTHDAY", _user.get("BIRTHDAY"));
                  //  jsonObject.put("AGE", _user.getAge());
                    jsonObject.put("ZZMMNAME", _user.get("ZZMMNAME"));
                    jsonObject.put("JNAME", _user.get("JNAME"));
                    jsonObject.put("EDUCATIONNAME", (_user.get("EDUCATIONNAME")== null ? "" : _user.get("EDUCATIONNAME")));
                    jsonObject.put("TEL", _user.get("TEL"));
                    jsonObject.put("STATE", _user.get("STATE"));
                    jsonObject.put("SXBZ", (_user.get("SXBZ")== null ? "" : _user.get("SXBZ")));
                    jsonObject.put("STATEb",  (_user.get("OP1")== null ? "未公布" : _user.get("OP1")));
                    jsonArray.add(jsonObject);
                    num++;
                }
            }

            LayuiDataTableResultBean result = new LayuiDataTableResultBean();
            result.setCode(0);
            result.setMsg("success");
            result.setCount((int) allcount);
            result.setData(jsonArray);

            return result;
        } catch (Exception e) {
            e.printStackTrace();

            LayuiDataTableResultBean result = new LayuiDataTableResultBean();
            result.setCount(-1);
            result.setMsg("err");
            return result;
        }
    }

//[end]

    //[start] 备注信息

    @RequestMapping("/bz")
    public String BZ(HttpServletRequest request, Model model) {
        try {
            model.addAttribute("path", request.getContextPath());
            String id = request.getParameter("id").trim();
            model.addAttribute("id", id);

            DUserResume resume = nzService.getDuserResume(id);
            model.addAttribute("bz", resume.getSxbz());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "Do/Internal/Resume/bz";
    }

    @RequestMapping(value = "/SaveBZ", method = RequestMethod.POST)
    public void SaveBZ(HttpServletRequest request, HttpServletResponse response) {
        try {
            String id = request.getParameter("id").trim();
            DUserResume resume = nzService.getDuserResume(id);
            resume.setSxbz(request.getParameter("sxbz"));

            utilService.editObject(resume);
            utilService.printJsonResult(true, resume.getSxbz(), "no", response);

        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败！", "no", response);
        }
    }

    //[end]

    //[start] 简历筛选结果

    @RequestMapping(value = "/SaveAction", method = RequestMethod.POST)
    public void SaveAction(HttpServletRequest request, HttpServletResponse response, NZUserForm resume) {
        try {
            String fid = request.getParameter("fid").trim();//招聘流程ID
            String deptcode = request.getParameter("deptcode").trim();//责任部门编码

            BaseUser cuser = utilService.getSessionUser(request);
            if (cuser.getUdept().equals(deptcode)) {
                //流程是否结束
                if (utilService.FlowIsDoing(fid)) {
                    Date time = new Date();
                    List<DNZResume> editlist = new ArrayList<DNZResume>();
                    for (DNZResume user : resume.getResume()) {
                        DNZResume usr = nzService.getDResume(user.getId());
                        if (!usr.getState().equals(user.getState())
                                && usr.getFid().equals(fid)
                                && usr.getFqstate().equals("未放弃")) {
                            usr.setEditDate(time);
                            usr.setEditUserid(cuser.getId());
                            usr.setEditUserName(cuser.getUname());
                            usr.setState(user.getState());

                            editlist.add(usr);
                        }
                    }
                    if (editlist.size() > 0) {
                        utilService.editList(editlist);
                        utilService.printJsonResult(true, "操作成功！", "no", response);
                    } else {
                        utilService.printJsonResult(false, "当前信息不能执行此操作！", "no", response);
                    }
                } else {
                    utilService.printJsonResult(false, "当前流程不支持此操作！", "no", response);
                }
            } else {
                utilService.printJsonResult(false, "您无权执行此操作！", "no", response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败！", "no", response);
        }
    }

    //[end]

    //[start] 流程扭转到下一步

    @SuppressWarnings({"rawtypes", "unchecked"})
    @RequestMapping(value = "/NextAction", method = RequestMethod.POST)
    public void NextAction(HttpServletRequest request, HttpServletResponse response) {
        try {
            String[] ids = request.getParameterValues("id");//人员信息ID
            if (ids != null) {
                String pid = request.getParameter("pid").trim();//招聘方案ID
                String fid = request.getParameter("fid").trim();//招聘流程ID
                String deptcode = request.getParameter("deptcode").trim();//责任部门编码
                BaseUser usr = utilService.getSessionUser(request);
                if (usr.getUdept().equals(deptcode)) {
                    //流程是否结束
                    if (utilService.FlowIsDoing(fid)) {
                        List editlist = new ArrayList();
                        List<DUserResume> users = doResumeService.getDUserResumes(pid, ids);
                        ProjectInfoFlow nFlow = nzService.getNextFlow(pid, deptcode, fid);

                        for (DUserResume user : users) {
                            if (user.getFid().equals(fid)
                                    && (user.getState().equals("通过")||user.getState().equals("已通过")||user.getState().equals("已通过"))
                                    && user.getFqstate().equals("未放弃")
                                    && user.getNrid() == null) {
                                user.setFid(nFlow.getId());
                                user.setPath(user.getPath() + nFlow.getId() + "/");
                                editlist.add(user);
                            }
                        }

                        if (editlist.size() > 0) {
                            nFlow.setState(EnumTools.PlanFlowState.进行中.ordinal());
                            editlist.add(nFlow);

                            utilService.editList(editlist);
                            utilService.printJsonResult(true, "操作成功！", "no", response);
                        } else {
                            utilService.printJsonResult(false, "当前选中的信息不能执行此操作！", "no", response);
                        }
                    } else {
                        utilService.printJsonResult(false, "当前流程不支持此操作！", "no", response);
                    }
                } else {
                    utilService.printJsonResult(false, "您无权执行此操作！", "no", response);
                }
            } else {
                utilService.printJsonResult(false, "请选择人员信息！", "no", response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败！", "no", response);
        }
    }

    //[end]


    //[start] 通过简历筛选
    @RequestMapping(value = "/ResumeOkAction", method = RequestMethod.POST)
    public void ResumeOkAction(HttpServletRequest request, HttpServletResponse response) {
        try {
            String fid = request.getParameter("fid").trim();//招聘流程ID
            String deptcode = request.getParameter("deptcode").trim();//责任部门编码

            BaseUser cuser = utilService.getSessionUser(request);
            if (cuser.getUdept().equals(deptcode)) {
                //流程是否结束
                if (utilService.FlowIsDoing(fid)) {
                    String[] ids = request.getParameterValues("id");
                    if (ids != null) {
                        List<DUserResume> editList = new ArrayList<DUserResume>();
                        List<DUserResume> resumes = doResumeService.getResumes(ids);
                        for (DUserResume resume : resumes) {
                            if (resume.getFid().equals(fid)
                                    && resume.getFqstate().equals("未放弃")
                                    && resume.getNrid() == null) {
                                resume.setState("已通过");
                                resume.setEditDate(new Date());
                                resume.setEditUserid(cuser.getId());
                                resume.setEditUserName(cuser.getUname());
                                editList.add(resume);
                            }
                        }
                        if (editList.size() > 0) {
                            utilService.editList(editList);
                            utilService.printJsonResult(true, "操作成功！", "no", response);
                        } else {
                            utilService.printJsonResult(false, "当前选中的简历不能执行此操作！", "no", response);
                        }
                    } else {
                        utilService.printJsonResult(false, "请选择应聘者！", "no", response);
                    }
                } else {
                    utilService.printJsonResult(false, "当前流程不支持此操作！", "no", response);
                }
            } else {
                utilService.printJsonResult(false, "您无权执行此操作！", "no", response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败！", "no", response);
        }
    }

    @RequestMapping(value = "/ResumeNoAction", method = RequestMethod.POST)
    public void ResumeNoAction(HttpServletRequest request, HttpServletResponse response) {
        try {
            String fid = request.getParameter("fid").trim();//招聘流程ID
            String deptcode = request.getParameter("deptcode").trim();//责任部门编码

            BaseUser cuser = utilService.getSessionUser(request);
            if (cuser.getUdept().equals(deptcode)) {
                //流程是否结束
                if (utilService.FlowIsDoing(fid)) {
                    DUserResume resume = doResumeService.getDUserResume(request.getParameter("id").trim());
                    if (resume.getFid().equals(fid)
                            && resume.getFqstate().equals("未放弃")
                            && resume.getNrid() == null) {
                        resume.setState("未通过");
                        resume.setOp1("未公布");
                        resume.setSxbz(request.getParameter("sxbz"));
                        resume.setEditDate(new Date());
                        resume.setEditUserid(cuser.getId());
                        resume.setEditUserName(cuser.getUname());

                        utilService.editObject(resume);
                        utilService.printJsonResult(true, "操作成功！", "no", response);
                    } else {
                        utilService.printJsonResult(false, "选中的简历不能执行此操作", "no", response);
                    }
                } else {
                    utilService.printJsonResult(false, "当前流程不支持此操作！", "no", response);
                }
            } else {
                utilService.printJsonResult(false, "您无权执行此操作！", "no", response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败！", "no", response);
        }
    }


    //[start] 未通过简历筛选
    @RequestMapping(value = "/ResumeAllNoAction", method = RequestMethod.POST)
    public void ResumeAllNoAction(HttpServletRequest request, HttpServletResponse response) {
        try {
            String fid = request.getParameter("fid").trim();//招聘流程ID
            String deptcode = request.getParameter("deptcode").trim();//责任部门编码
            BaseUser cuser = utilService.getSessionUser(request);

            if (cuser.getUdept().equals(deptcode)) {
                //流程是否结束
                if (utilService.FlowIsDoing(fid)) {
                    String sid=request.getParameter("ids");
                    String[] ids=sid.split(",");
                    if(ids!=null&&ids.length>0){
                        List<DUserResume> editList = new ArrayList<DUserResume>();
                        List<DUserResume> resumes = doResumeService.getResumes(ids);
                        String sxbz=request.getParameter("sxbz");
                        for (DUserResume resume : resumes) {
                            if (resume.getFid().equals(fid)
                                    && resume.getFqstate().equals("未放弃")
                                    && resume.getNrid() == null) {
                                resume.setState("未通过");
                                resume.setSxbz(sxbz);
                                resume.setEditDate(new Date());
                                resume.setEditUserid(cuser.getId());
                                resume.setEditUserName(cuser.getUname());
                                editList.add(resume);
                            }
                        }
                        if (editList.size() > 0) {
                            utilService.editList(editList);
                            utilService.printJsonResult(true, "操作成功！", "no", response);
                        } else {
                            utilService.printJsonResult(false, "当前选中的简历不能执行此操作！", "no", response);
                        }

                    }else {
                        utilService.printJsonResult(false, "请至少选择应聘者！", "no", response);
                    }
                } else {
                    utilService.printJsonResult(false, "当前流程不支持此操作！", "no", response);
                }
            } else {
                utilService.printJsonResult(false, "您无权执行此操作！", "no", response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败！", "no", response);
        }
    }




}
